<template>
  <div class="my-registrations">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><Tickets /></el-icon>
        我的报名
      </h2>
      <div class="header-actions">
        <el-button @click="loadRegistrations" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ stats.total }}</div>
            <div class="stat-label">总报名</div>
          </div>
          <el-icon class="stat-icon total"><Tickets /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ stats.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
          <el-icon class="stat-icon pending"><Clock /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ stats.approved }}</div>
            <div class="stat-label">已通过</div>
          </div>
          <el-icon class="stat-icon approved"><CircleCheck /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ stats.rejected }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
          <el-icon class="stat-icon rejected"><CircleClose /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="状态">
          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动类型">
          <el-select
            v-model="filterForm.activityType"
            placeholder="选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="学术类" value="ACADEMIC" />
            <el-option label="文体类" value="CULTURAL" />
            <el-option label="志愿服务" value="VOLUNTEER" />
            <el-option label="社团活动" value="CLUB" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 报名列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <span class="list-title">
            报名记录
            <el-tag v-if="total > 0" type="info" size="small">
              共 {{ total }} 条记录
            </el-tag>
          </span>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="registrations.length === 0" class="empty-container">
        <el-empty description="暂无报名记录">
          <el-button type="primary" @click="$router.push('/student/activities')">
            去报名活动
          </el-button>
        </el-empty>
      </div>
      
      <!-- 报名列表 -->
      <div v-else class="registration-list">
        <div 
          v-for="registration in registrations" 
          :key="registration.id"
          class="registration-item"
        >
          <div class="item-content">
            <!-- 活动信息 -->
            <div class="activity-info">
              <div class="activity-header">
                <h3 class="activity-title" @click="goToActivity(registration.activity.id)">
                  {{ registration.activity.title }}
                </h3>
                <div class="activity-tags">
                  <el-tag :type="getStatusType(registration.status)" size="small">
                    {{ getStatusText(registration.status) }}
                  </el-tag>
                  <el-tag type="info" size="small">
                    {{ getActivityTypeText(registration.activity.type) }}
                  </el-tag>
                </div>
              </div>
              
              <div class="activity-meta">
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDate(registration.activity.startTime, 'MM-DD HH:mm') }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ registration.activity.location }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>报名时间：{{ formatDate(registration.registrationTime, 'MM-DD HH:mm') }}</span>
                </div>
              </div>
              
              <p class="activity-description">{{ registration.activity.description }}</p>
            </div>
            
            <!-- 报名详情 -->
            <div class="registration-details">
              <div v-if="registration.status === 'REJECTED' && registration.rejectReason" class="reject-reason">
                <el-alert
                  title="拒绝原因"
                  :description="registration.rejectReason"
                  type="error"
                  :closable="false"
                  show-icon
                />
              </div>
              
              <div v-if="registration.notes" class="registration-notes">
                <div class="notes-label">备注信息：</div>
                <div class="notes-content">{{ registration.notes }}</div>
              </div>
              
              <div v-if="registration.approvalTime" class="approval-info">
                <div class="approval-label">审核时间：</div>
                <div class="approval-time">{{ formatDate(registration.approvalTime) }}</div>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="item-actions">
            <el-button 
              type="primary" 
              size="small"
              @click="goToActivity(registration.activity.id)"
            >
              查看详情
            </el-button>
            
            <el-button 
              v-if="canCancel(registration)"
              type="danger" 
              size="small"
              @click="handleCancel(registration)"
            >
              取消报名
            </el-button>
            
            <el-button 
              v-if="canFeedback(registration)"
              type="success" 
              size="small"
              @click="goToFeedback(registration.activity.id)"
            >
              活动反馈
            </el-button>
            
            <el-dropdown v-if="hasMoreActions(registration)" trigger="click">
              <el-button size="small">
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadCertificate(registration)">
                    <el-icon><Download /></el-icon>
                    下载证书
                  </el-dropdown-item>
                  <el-dropdown-item @click="shareActivity(registration.activity)">
                    <el-icon><Share /></el-icon>
                    分享活动
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { formatDate, debounce } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Tickets,
  Refresh,
  Clock,
  CircleCheck,
  CircleClose,
  Search,
  Location,
  Calendar,
  ArrowDown,
  Download,
  Share
} from '@element-plus/icons-vue'

const router = useRouter()

const loading = ref(false)
const registrations = ref([])
const total = ref(0)

const filterForm = reactive({
  status: '',
  activityType: '',
  dateRange: null
})

const pagination = reactive({
  page: 1,
  size: 10
})

// 统计数据
const stats = computed(() => {
  const total = registrations.value.length
  const pending = registrations.value.filter(r => r.status === 'PENDING').length
  const approved = registrations.value.filter(r => r.status === 'APPROVED').length
  const rejected = registrations.value.filter(r => r.status === 'REJECTED').length
  
  return { total, pending, approved, rejected }
})

const getStatusType = (status) => {
  const typeMap = {
    PENDING: 'warning',
    APPROVED: 'success',
    REJECTED: 'danger',
    CANCELLED: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    PENDING: '待审核',
    APPROVED: '已通过',
    REJECTED: '已拒绝',
    CANCELLED: '已取消'
  }
  return textMap[status] || status
}

const getActivityTypeText = (type) => {
  const typeMap = {
    ACADEMIC: '学术类',
    CULTURAL: '文体类',
    VOLUNTEER: '志愿服务',
    CLUB: '社团活动',
    OTHER: '其他'
  }
  return typeMap[type] || type
}

const canCancel = (registration) => {
  return registration.status === 'PENDING' || registration.status === 'APPROVED'
}

const canFeedback = (registration) => {
  if (registration.status !== 'APPROVED') return false
  const activityEndTime = new Date(registration.activity.endTime)
  const now = new Date()
  return activityEndTime < now
}

const hasMoreActions = (registration) => {
  return registration.status === 'APPROVED'
}

const loadRegistrations = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filterForm
    }
    
    // 处理日期范围
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }
    
    const response = await api.get('/registrations/my', { params })
    const { data, total: totalCount } = response.data.data
    
    registrations.value = data || []
    total.value = totalCount || 0
    
  } catch (error) {
    console.error('加载报名记录失败:', error)
    ElMessage.error('加载报名记录失败')
  } finally {
    loading.value = false
  }
}

const handleFilter = debounce(() => {
  pagination.page = 1
  loadRegistrations()
}, 300)

const handleReset = () => {
  Object.assign(filterForm, {
    status: '',
    activityType: '',
    dateRange: null
  })
  pagination.page = 1
  loadRegistrations()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadRegistrations()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadRegistrations()
}

const goToActivity = (activityId) => {
  router.push(`/student/activities/${activityId}`)
}

const goToFeedback = (activityId) => {
  router.push(`/student/feedback/${activityId}`)
}

const handleCancel = async (registration) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消报名「${registration.activity.title}」吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/registrations/${registration.id}`)
    
    ElMessage.success('取消报名成功')
    loadRegistrations()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
      ElMessage.error(error.message || '取消报名失败')
    }
  }
}

const downloadCertificate = async (registration) => {
  try {
    const response = await api.get(`/registrations/${registration.id}/certificate`, {
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${registration.activity.title}-参与证书.pdf`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('证书下载成功')
    
  } catch (error) {
    console.error('下载证书失败:', error)
    ElMessage.error('下载证书失败')
  }
}

const shareActivity = async (activity) => {
  try {
    const shareData = {
      title: activity.title,
      text: activity.description,
      url: `${window.location.origin}/student/activities/${activity.id}`
    }
    
    if (navigator.share) {
      await navigator.share(shareData)
    } else {
      await navigator.clipboard.writeText(shareData.url)
      ElMessage.success('活动链接已复制到剪贴板')
    }
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

onMounted(() => {
  loadRegistrations()
})
</script>

<style scoped>
.my-registrations {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-content {
  position: relative;
  z-index: 2;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32px;
  opacity: 0.3;
}

.stat-icon.total {
  color: #409eff;
}

.stat-icon.pending {
  color: #e6a23c;
}

.stat-icon.approved {
  color: #67c23a;
}

.stat-icon.rejected {
  color: #f56c6c;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.list-card {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px 20px;
  text-align: center;
}

.registration-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.registration-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
  transition: all 0.3s ease;
}

.registration-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-content {
  flex: 1;
  margin-right: 20px;
}

.activity-info {
  margin-bottom: 16px;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.activity-title {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  margin: 0;
  cursor: pointer;
  flex: 1;
  margin-right: 12px;
}

.activity-title:hover {
  text-decoration: underline;
}

.activity-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.activity-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.activity-description {
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.registration-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reject-reason {
  margin-top: 12px;
}

.registration-notes,
.approval-info {
  display: flex;
  gap: 8px;
  font-size: 14px;
}

.notes-label,
.approval-label {
  color: #909399;
  min-width: 80px;
}

.notes-content,
.approval-time {
  color: #606266;
  flex: 1;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 120px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .registration-item {
    flex-direction: column;
    gap: 16px;
  }
  
  .item-content {
    margin-right: 0;
  }
  
  .item-actions {
    flex-direction: row;
    flex-wrap: wrap;
    min-width: auto;
    width: 100%;
  }
  
  .activity-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .activity-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>